//
//  PicturePickerController.swift
//  15-照片选择
//
//  Created by 高伦展 on 2018/2/24.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit

private let PicturePickerCellId = "Cell"

private let PicturePickerMaxCount = 4

class PicturePickerController: UICollectionViewController {

    lazy var pictures = [UIImage]()
    
    var selectedIndex = 0
    
    init() {
        super.init(collectionViewLayout:PicturePickerlLayout())
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //在 collectionViewController 中 collectionView != view
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId)

        // Do any additional setup after loading the view.
    }
    
    //MARK: - 照片选择器布局
    private class PicturePickerlLayout:UICollectionViewFlowLayout{
        
        override func prepare() {
            super.prepare()
            
            //不建议过分依赖 UIScreen 作为布局参照
            let count:CGFloat = 4
            let margin = UIScreen.main.scale * 4
            
            let w = (collectionView!.bounds.width - (count + 1) * margin) / count
            
            itemSize = CGSize(width: w, height: w)
            
            sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
            minimumLineSpacing = margin
            minimumInteritemSpacing = margin
        }
    }
 
}

extension PicturePickerController{
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        
        //保证末尾有一个加号按钮，如果达到上限，不显示 + 按钮
        return pictures.count + (pictures.count == PicturePickerMaxCount ? 0 : 1)
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PicturePickerCellId, for: indexPath) as! PicturePickerCell
        
        // Configure the cell
        
        //cell.backgroundColor = UIColor.red
        //设置图片
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil
        //设置代理
        cell.pictureDelegate = self
        
        return cell
    }
}

extension PicturePickerController:PicturePickerCellDelegate{
    
    func picturePickerCellDidAdd(cell: PicturePickerCell) {
       
        /**
         判断是否允许访问相册
         photoLibrary：保存的照片（可以删除） +  同步的照片（不允许删除）
         
         */
        
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            return
        }
        
        selectedIndex = (collectionView?.indexPath(for: cell)?.item) ?? 0
        
        let picker = UIImagePickerController()
        picker.delegate = self
        
        present(picker, animated: true, completion: nil)
    }
    
    func picturePickerCellDidRemove(cell: PicturePickerCell) {
        
        let indexPath = collectionView?.indexPath(for: cell)!
        
        if (indexPath?.item)! >= pictures.count{
            return
        }
        
        pictures.remove(at: (indexPath?.item)!)
        
        collectionView?.reloadData()
        
        //collectionView?.deleteItems(at: [indexPath!])
    }
}

extension PicturePickerController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //照片选择完成
    //提示：一旦实现代理方法，必须自己 dismiss
    // 如果使用 cocos2dx 开发一个 ‘空白的模版’游戏， 内存占用 70M，IOS UI的空白应用程序，大概 19M
    // 一般应用程序 内存在 100M
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //print(info)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        let scaleImage = image.scaleToWith(width: 600)
        
        if selectedIndex >= pictures.count{
            pictures.append(scaleImage)
        }else{
            pictures[selectedIndex] = scaleImage
        }
        
        collectionView?.reloadData()
        
        dismiss(animated: true, completion: nil)
    }
    
}

///PicturePickerCellDelegate 代理
/// 如果协议中包含 optional 的函数，协议需要使用 @objc 修饰
@objc
protocol PicturePickerCellDelegate:NSObjectProtocol{
    
    @objc optional func picturePickerCellDidAdd(cell:PicturePickerCell)
    @objc optional func picturePickerCellDidRemove(cell:PicturePickerCell)
    
}

//照片选择 Cell
class PicturePickerCell: UICollectionViewCell {
    
    var image:UIImage?{
        didSet{
            addButton.setImage(image ?? UIImage(named:"compose_pic_add"), for: .normal)
            //隐藏删除按钮 image == nil 就是新增按钮
            removeButton.isHidden = (image == nil)
        }
    }
    
    ///照片选择代理
    weak var pictureDelegate : PicturePickerCellDelegate?
    
    //MARK: - 监听方法
    @objc func addPicture() {
        pictureDelegate?.picturePickerCellDidAdd?(cell: self)
    }
    
    @objc func removePicture() {
        pictureDelegate?.picturePickerCellDidRemove?(cell: self)
    }
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()
    {
        //添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        //设置布局
        addButton.frame = bounds
        
        removeButton.snp.makeConstraints { (make) in
            make.top.equalTo(contentView.snp.top)
            make.right.equalTo(contentView.snp.right)
        }
        
        //添加事件
        addButton.addTarget(self, action: #selector(PicturePickerCell.addPicture), for: .touchUpInside)
        removeButton.addTarget(self, action: #selector(PicturePickerCell.removePicture), for: .touchUpInside)
        
        //图片填充模式
        addButton.imageView?.contentMode = .scaleAspectFill
    }
    
    private lazy var addButton:UIButton = UIButton(imgName: "compose_pic_add", bgImgName: nil)
    
    private lazy var removeButton:UIButton = UIButton(imgName: "compose_photo_close", bgImgName: nil)
}

